﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PeerToPeer
{
    public partial class FrmUdpPeer : Form
    {
        public FrmUdpPeer()
        {
            InitializeComponent();
        }
        UdpClient udpClient=null;
        IPEndPoint remoteIpEndPoint = null;
        private void btn_Connention_Click(object sender, EventArgs e)
        {
            Task.Run(new Action(() => { Connection(); }));
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (this.udpClient != null)
            {
                //.Send() 
                var data = Encoding.UTF8.GetBytes(txt_Msg.Text);
                PushMsg($"发送消息:{txt_Msg.Text}\r\n");
                udpClient.Send(data, data.Length, remoteIpEndPoint);
            }
        }
        private void Connection()
        {
            string localEndPoint;
            int port;
            IPEndPoint iPEndPoint;
            string ip;
            using (var tcpClient = new UdpClient())
            {
                tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //tcpClient.Connect("外网IP", 3721);
                                
                IPEndPoint iPEndPoint1 = new IPEndPoint(IPAddress.Parse("外网IP"), 3722);
                var bytes = Encoding.UTF8.GetBytes("1");
                tcpClient.Send(bytes, bytes.Length, iPEndPoint1);
                PushMsg("成功链接服务器！\r\n");
                var socket = tcpClient.Client;
                localEndPoint = socket.LocalEndPoint.ToString();
                var hostname = localEndPoint.Split(':')[0];
                port = int.Parse(localEndPoint.Split(':')[1]);
                PushMsg($"本地ip:{hostname}本地端口{port}！\r\n");
                iPEndPoint = new IPEndPoint(IPAddress.Parse(hostname), port);
                bytes = tcpClient.Receive(ref remoteIpEndPoint);
                // var readerStream = new StreamReader();
                ip =Encoding.UTF8.GetString(bytes);
                PushMsg($"成功获取对方ip！{ip}\r\n");
                //tcpClient.Client.Shutdown(SocketShutdown.Both);
                tcpClient.Close();
                tcpClient.Dispose();
            }
            var tcpClient2 = new UdpClient();
            tcpClient2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            tcpClient2.Client.Bind(iPEndPoint);
            this.udpClient = tcpClient2;
            PushMsg($"开始链接对方！{ip}\r\n");
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    
                    var yp = int.Parse(ip.Split(':')[1]);
                   // tcpClient2.Connect(ip.Split(':')[0], yp);
                    
                    var bytes = Encoding.UTF8.GetBytes("1");
                    IPEndPoint iPEndPoint1 = new IPEndPoint(IPAddress.Parse(ip.Split(':')[0]), yp);
                    this.remoteIpEndPoint = iPEndPoint1;
                    this.udpClient.Send(bytes, bytes.Length, iPEndPoint1);
                    //PushMsg($"链接成功！{ip}\r\n");
                    this.BeginInvoke(new Action(() => {
                        btn_Send.Enabled = true;
                    }));
                    //Thread.Sleep(1000);
                    break;
                }
                catch (Exception ex)
                {

                    PushMsg(ex.Message + "\r\n");
                }
            }
            var bytes2 = this.udpClient.Receive(ref remoteIpEndPoint);
            PushMsg($"\r\n接收到消息:{Encoding.UTF8.GetString(bytes2)}\r\n");
            Task.Run(() =>
            {
               // this.stream = tcpClient2.GetStream();
                PushMsg($"开始监听接收信息！\r\n");
                while (true)
                {
                    try
                    {
                        var bytedd = new byte[tcpClient2.Client.ReceiveBufferSize];
                        var bytes = tcpClient2.Receive(ref remoteIpEndPoint); 
                        var result = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                        PushMsg($"接收到消息:{result}\r\n");
                    }
                    catch (Exception ex)
                    {
                        PushMsg($"接收错误{ex.Message}\r\n");
                        break;
                    }
                }
            });
        }
        private void PushMsg(string Msg)
        {
            this.BeginInvoke(new Action(() =>
            {
                rtb_Msg.AppendText(Msg);
            }));
        }
    }
}
